# coding:utf-8

from bson import ObjectId
import tornado
from tornado import gen
from tornado.web import HTTPError

from handler.api import errors
from handler.api.base import BaseHandler

import config
from data.redis import redis
from data.mongo import col_noise_event,col_noise_event_data,col_resample_event_data

import datetime
import json
import struct
# from data.collections import User, School
#from util.token import token_manager
class NoiseConfigHandler(BaseHandler):
    def get(self):
        # 读取配置
        with open('noise_config.json', 'r') as f:
            config = f.read()
        service_config = json.loads(config)
        data_json={
                    "noise_limit_1":int(service_config["noise_limit_1"]),\
                    "noise_limit_2":int(service_config["noise_limit_2"])\
                    }
        self.write_json(data_json)
 
class NoiseSensorListHandler(BaseHandler):
    def get(self):
    
        # 读取配置
        with open('noise_config.json', 'r') as f:
            config = f.read()
        service_config = json.loads(config)
        GateWayList=service_config["GateWayList"]
        
        sensorList=[]
        
        for item in GateWayList:
            j=0
            for i in item["ConnectList"]:
                j+=1
                if i == 1:
                    #传感器编号
                    sensorID=item["GateWayID"]+"_0"+str(j)
            
                    # redis_last_vibration_leve_time_key = "last_vibration_time_01D9A057_01"
                    # redis_last_time=""
                    # #redis_last_time = redis.lrange(redis_last_vibration_leve_time_key,0,4)[3]
                    #samples_co_name="samples_"+sensorID
                    #samples_last=col_samples_01["samples_co_name"].find().sort([("samples_time",-1)]).limit(1)#[0]["samples_time"]
                    
                    redis_last_time=""
                    #samples_time_key="last_time_samples_" + sensorID[0:-3]
                    #samples_time_key="last_second_samples_" + sensorID
                    samples_time_key="last_second_LP_A_" + sensorID
                    #print(sensorID)
                    #redis_last_time=redis.get(samples_time_key)
                    #print(json.loads(redis.lrange(samples_time_key,0,1)[0])["samples_time"])
                    #print(samples_time_key)
                    #redis_last_time=json.loads(redis.lrange(samples_time_key,0,1)[0])["samples_time"]
                    redis_last_time=json.loads(redis.get(samples_time_key))['samples_time']
                    #print(redis_last_time)
                    # for samples_item in samples_last:
                        # redis_last_time=samples_item["samples_time"]
                    noiseLimit1=col_noise_event.find({"sensorID":sensorID,"event_type":'1'}).count()
                    noiseLimit2=col_noise_event.find({"sensorID":sensorID,"event_type":'2'}).count()
                    item1={"sensorID":sensorID,\
                             "noiseLimit1":noiseLimit1,\
                             "noiseLimit2":noiseLimit2,\
                             "lastCollectTime":redis_last_time}
                    #print(item1)
                    sensorList.append(item1)
        data_json = {"sensors":sensorList}
        self.write_json(data_json)

class NoisRealTimeLP_AHandler(BaseHandler):
    def get(self):
        sensorID = self.get_argument('sensorID')
        samples_data_key = "last_second_LP_A_" + sensorID
        #samples_time_key = "last_time_vibration_leve_samples_" + sensorID
        
        redis_last_LP_A_time=[]
        redis_last_LP_A_data=[]
        
        samples_data=json.loads(redis.get(samples_data_key))
        redis_last_LP_A_time.append(samples_data['samples_time'])
        redis_last_LP_A_data.append(samples_data['LP_A'])
        
        data_json = {"vibrationLeveList":[{"time":redis_last_LP_A_time},
                                          {"data":redis_last_LP_A_data}]}
        self.write_json(data_json)

class NoiseEventListHandler(BaseHandler):
    def get(self):
        sensorID = self.get_argument('sensorID')
        limit_1 = self.get_argument('limit_1')
        limit_2 = self.get_argument('limit_2')
        
        limit = self.get_argument('limit')
        offset = self.get_argument('offset')
        #print(limit)
        #print(offset)
        
        event_data=col_noise_event.find({"sensorID":sensorID,'$or':[{'event_type':limit_1},{'event_type':limit_2}]},{"_id":0}).sort([("event_start_time",-1)]).limit(int(limit)).skip(int(offset))
        event_data_count=col_noise_event.find({"sensorID":sensorID,'$or':[{'event_type':limit_1},{'event_type':limit_2}]},{"_id":0}).sort([("event_start_time",-1)]).count()
        #print(event_data_count)
        #print(event_data)
        event_list=[]
        for item in event_data:
            event_list.append(item)
        data_json = {"eventList":event_list,"total":event_data_count}
        self.write_json(data_json)

class NoiseEventDataHandler(BaseHandler):
    def get(self):
        #print(datetime.datetime.now())
        eventID = self.get_argument('eventID')
        #print(eventID)
        samples_data=col_resample_event_data.find({"event_id":eventID}).sort([("samples_data_time",1)])
        time_list=[]
        data_list=[]
        str_item=''
        first=0
        for item_2 in samples_data:
            data_list+=item_2['samples_data']
            if first == 0:
                str_item=item_2["samples_data_time"]
                first =1
        #print(str_item)
        start_time=datetime.datetime.strptime(str_item,'%Y-%m-%d %H:%M:%S.%f')
        samples_data.close()
        
        for j in range(len(data_list)):
            sing_time=start_time+datetime.timedelta(seconds=0.002*j)
            sing_time_str=sing_time.strftime("%Y-%m-%d %H:%M:%S.%f")[0:23]
            time_list.append(sing_time_str)
            
        #print(datetime.datetime.now())
            
        data_json = {"vibrationLeveList":[{"time":time_list},
                                          {"data":data_list}]}
        #print(datetime.datetime.now())
        self.write_json(data_json)
